# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from rest_framework.generics import CreateAPIView
from rest_framework.views import APIView
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.parsers import FormParser, JSONParser
from rest_framework.response import Response

from wechat.serializers import MenuSerializer
from wechat.models import Menu

# Create your views here.


class CreateMenuItem(APIView):
    """
    创建微信公众号菜单选项
    """
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication,)
    parser_classes = (FormParser, JSONParser)

    def post(self, request, *args, **kwargs):
        data = request.data.copy()
        menu_serialize = MenuSerializer(data=data)
        menu_serialize.initial_data['member'] = request.user.id
        if menu_serialize.is_valid():
            menu_serialize.save()
            ret = {
                'code': 200,
                'msg': '创建成功',
                'menu': menu_serialize.data
            }
            return Response(ret)
        else:
            ret = {
                'code': 400,
                'msg': '创建失败',
                'error': menu_serialize._errors
            }
            return Response(ret)


class UpdateMenuItem(APIView):
    """
    更新微信公众号菜单选项
    """
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication,)
    parser_classes = (FormParser, JSONParser)

    def post(self, request, *args, **kwargs):
        m_id = kwargs['m_id']
        try:
            menu = Menu.objects.get(pk=m_id, member=request.user)
            m_serialize = MenuSerializer(instance=menu, data=request.data)
            if m_serialize.is_valid():
                m_serialize.save()
                ret = {
                    'code': 200,
                    'msg': '更新成功',
                    'menu': m_serialize.data
                }
                return Response(ret)
            else:
                ret = {
                    'code': 400,
                    'msg': '跟新失败',
                    'error': m_serialize.errors()
                }
                return Response(ret)
        except Menu.DoesNotExist:
            ret = {
                'code': 404,
                'msg': '菜单没有找到'
            }
            return Response(ret)


class DeleteMenuItem(APIView):
    """
    删除微信公众号菜单选项
    """
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication,)
    parser_classes = (FormParser, JSONParser)

    def post(self, request, *args, **kwargs):
        m_id = kwargs['m_id']
        try:
            Menu.objects.get(pk=m_id, member=request.user).delete()
            ret = {
                'code': 200,
                'msg': '删除成功'
            }
            return Response(ret)
        except Menu.DoesNotExist:
            ret = {
                'code': 404,
                'msg': '菜单没有找到'
            }
            return Response(ret)


class CreateMenu(APIView):
    """
    创建微信菜单，调用微信接口
    """
    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication,)
    parser_classes = (FormParser, JSONParser)

    def post(self, request, *args, **kwargs):
        pass


class MenuList(APIView):
    """获取菜单列表"""

    permission_classes = (IsAuthenticated,)
    authentication_classes = (SessionAuthentication,)
    parser_classes = (FormParser, JSONParser)

    def make_menu(self, menu):
        menu_json = {
            'id': menu.id,
            'name': menu.name,
            'type': menu.mtype,
        }
        if menu.key:
            menu_json['key'] = menu.key
        if menu.url:
            menu_json['url'] = menu.url
        if menu.media_id:
            menu_json['media_id'] = menu.media_id
        if menu.appid:
            menu_json['appid'] = menu.appid
        if menu.pagepath:
            menu_json['pagepath'] = menu.pagepath
        return menu_json

    def get(self, request, *args, **kwargs):
        menus = Menu.objects.filter(
            level=1, member=request.user).order_by('mindex')
        menu_array = []
        for menu in menus:
            sub_menu_array = []
            menu_json = self.make_menu(menu)
            sub_menus = Menu.objects.filter(
                level=2, parent_id=menu.id, member=request.user).order_by('mindex')
            for sub_menu in sub_menus:
                sub_menu_json = self.make_menu(sub_menu)
                sub_menu_array.append(sub_menu_json)

            menu_json['sub_button'] = sub_menu_array
            menu_array.append(menu_json)
        ret = {
            'code': 200,
            'msg': '获取成功',
            'menu': {
                'button': menu_array
            }
        }
        return Response(ret)
